package com.lekang.system.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.system.domain.CheckOutManagement;
import com.lekang.system.service.ICheckOutManagementService;
import com.lekang.system.service.IContractService;
import com.lekang.system.service.IBalanceService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 退住办理Controller
 * 
 * @author ruoyi
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/system/out_management")
public class CheckOutManagementController extends BaseController
{
    @Autowired
    private ICheckOutManagementService checkOutManagementService;
    
    @Autowired
    private IBalanceService balanceService;
    
    @Autowired
    private BalanceController balanceController;
    
    @Autowired
    private IContractService contractService;

    /**
     * 查询退住办理列表
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:list')")
    @GetMapping("/list")
    public TableDataInfo list(CheckOutManagement checkOutManagement)
    {
        startPage();
        
        // ✅ 权限控制：所有人都能看到退住申请数据，但只有护理员a能创建退住申请
        String currentUsername = getUsername();
        System.out.println("=== 退住管理权限检查 ===");
        System.out.println("当前用户: " + currentUsername);
        
        // 所有人都能看到所有退住申请数据（不进行数据过滤）
        System.out.println("✅ 所有用户都能看到退住申请数据");
        
        List<CheckOutManagement> list = checkOutManagementService.selectCheckOutManagementList(checkOutManagement);
        System.out.println("查询到的退住申请数量: " + (list != null ? list.size() : 0));
        return getDataTable(list);
    }

    /**
     * 导出退住办理列表
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:export')")
    @Log(title = "退住办理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheckOutManagement checkOutManagement)
    {
        List<CheckOutManagement> list = checkOutManagementService.selectCheckOutManagementList(checkOutManagement);
        ExcelUtil<CheckOutManagement> util = new ExcelUtil<CheckOutManagement>(CheckOutManagement.class);
        util.exportExcel(response, list, "退住办理数据");
    }

    /**
     * 获取退住办理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(checkOutManagementService.selectCheckOutManagementById(id));
    }
    
    /**
     * 根据业务ID获取退住办理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:query')")
    @GetMapping(value = "/business/{businessId}")
    public AjaxResult getInfoByBusinessId(@PathVariable("businessId") String businessId)
    {
        System.out.println("=== 根据业务ID查询退住办理信息 ===");
        System.out.println("业务ID: " + businessId);
        
        try {
            // 根据业务ID查询
            CheckOutManagement result = checkOutManagementService.selectCheckOutManagementByBusinessId(businessId);
            System.out.println("查询结果: " + (result != null ? "找到数据" : "未找到数据"));
            if (result != null) {
                System.out.println("老人姓名: " + result.getElderlyName());
                System.out.println("退住原因: " + result.getCheckOutReason());
            }
            return success(result);
        } catch (Exception e) {
            System.out.println("查询异常: " + e.getMessage());
            e.printStackTrace();
            return error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增退住办理
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:add')")
    @Log(title = "退住办理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheckOutManagement checkOutManagement)
    {
        // ✅ 权限控制：只有护理员a (huliyuana) 才能创建退住申请
        String currentUsername = getUsername();
        System.out.println("=== 退住申请创建权限检查 ===");
        System.out.println("当前用户: " + currentUsername);
        
        if (!"huliyuana".equals(currentUsername) && !getUserId().equals(1L)) {
            System.out.println("❌ 非护理员a，禁止创建退住申请");
            return error("只有护理员a才能创建退住申请");
        }
        
        System.out.println("✅ 护理员a，允许创建退住申请");
        return toAjax(checkOutManagementService.insertCheckOutManagement(checkOutManagement));
    }

    /**
     * 修改退住办理
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:edit')")
    @Log(title = "退住办理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CheckOutManagement checkOutManagement)
    {
        return toAjax(checkOutManagementService.updateCheckOutManagement(checkOutManagement));
    }

    /**
     * 删除退住办理
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:remove')")
    @Log(title = "退住办理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(checkOutManagementService.deleteCheckOutManagementByIds(ids));
    }
    
    /**
     * 根据老人ID获取合同信息
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:query')")
    @GetMapping("/contract/{elderlyId}")
    public AjaxResult getContractByElderlyId(@PathVariable("elderlyId") Long elderlyId)
    {
        try {
            System.out.println("=== 开始查询合同信息 ===");
            System.out.println("老人ID: " + elderlyId);
            
            // 创建查询条件
            com.lekang.system.domain.Contract contract = new com.lekang.system.domain.Contract();
            contract.setElderlyId(elderlyId);
            // 先不限制合同状态，查询所有合同
            // contract.setContractStatus("1"); // 查询有效合同
            
            // 查询合同列表
            java.util.List<com.lekang.system.domain.Contract> contracts = contractService.selectContractList(contract);
            
            System.out.println("查询到的合同数量: " + (contracts != null ? contracts.size() : 0));
            
            if (contracts != null && !contracts.isEmpty()) {
                // 打印所有找到的合同信息
                for (int i = 0; i < contracts.size(); i++) {
                    com.lekang.system.domain.Contract c = contracts.get(i);
                    System.out.println("合同" + (i+1) + ": ID=" + c.getId() + 
                                     ", 名称=" + c.getContractName() + 
                                     ", 状态=" + c.getContractStatus());
                }
                
                com.lekang.system.domain.Contract foundContract = contracts.get(0);
                System.out.println("返回第一个合同: " + foundContract.getContractName());
                // 返回第一个合同（不管状态）
                return success(foundContract);
            } else {
                System.out.println("未找到任何合同数据");
                return success(null); // 没有找到合同
            }
        } catch (Exception e) {
            System.out.println("查询合同信息异常: " + e.getMessage());
            e.printStackTrace();
            return error("获取合同信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取审批通过页面的完整数据
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:query')")
    @GetMapping("/approval-passed/{businessId}")
    public AjaxResult getApprovalPassedData(@PathVariable("businessId") Long businessId)
    {
        try {
            System.out.println("=== 获取审批通过数据 ===");
            System.out.println("业务ID: " + businessId);
            
            CheckOutManagement data = checkOutManagementService.getApprovalPassedData(businessId);
            
            if (data != null) {
                System.out.println("获取到审批通过数据: " + data.getCheckOutNo());
                return success(data);
            } else {
                System.out.println("未找到业务ID为 " + businessId + " 的审批通过数据");
                return error("未找到审批通过数据");
            }
        } catch (Exception e) {
            System.err.println("获取审批通过数据失败: " + e.getMessage());
            e.printStackTrace();
            return error("获取审批通过数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交解除合同（步骤3）
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:edit')")
    @Log(title = "解除合同提交", businessType = BusinessType.UPDATE)
    @PostMapping("/submitTermination")
    public AjaxResult submitTermination(@RequestBody java.util.Map<String, Object> params)
    {
        System.out.println("=== Controller：解除合同提交开始 ===");
        System.out.println("接收到的参数: " + params);
        
        try {
            // ✅ 权限控制：只有退住审批员a (tuizhushenpiyuana) 才能进行解除合同操作
            String currentUsername = getUsername();
            System.out.println("=== 解除合同权限检查 ===");
            System.out.println("当前用户: " + currentUsername);
            
            if (!"tuizhushenpiyuana".equals(currentUsername)) {
                System.out.println("❌ 非退住审批员a，禁止进行解除合同操作");
                return error("只有退住审批员a才能进行解除合同操作");
            }
            
            System.out.println("✅ 退住审批员a，允许进行解除合同操作");
            
            // 1. 提取参数
            Long businessId = Long.parseLong(params.get("businessId").toString());
            String contractNo = params.get("contractNo").toString();
            String fileName = params.get("fileName") != null ? params.get("fileName").toString() : "";
            
            // 处理 taskId - 避免空字符串
            String taskId = "";
            if (params.get("taskId") != null && !params.get("taskId").toString().trim().isEmpty()) {
                taskId = params.get("taskId").toString();
            }
            
            // 处理 ptId - 避免空字符串转Long
            Long ptId = null;
            if (params.get("ptId") != null && !params.get("ptId").toString().trim().isEmpty()) {
                try {
                    ptId = Long.parseLong(params.get("ptId").toString());
                } catch (NumberFormatException e) {
                    System.out.println("ptId 格式错误: " + params.get("ptId"));
                }
            }
            
            System.out.println("业务ID: " + businessId);
            System.out.println("合同编号: " + contractNo);
            System.out.println("文件名: " + fileName);
            System.out.println("当前任务ID: " + taskId);
            System.out.println("当前待办任务ID: " + ptId);
            
            // 2. ✅ 调用 Service 层处理所有业务逻辑
            int result = checkOutManagementService.submitTermination(businessId, contractNo, fileName, taskId, ptId);
            
            System.out.println("=== Controller：解除合同提交完成 ===");
            
            if (result > 0) {
                // ✅ 获取下一步的参数
                String nextTaskId = checkOutManagementService.getNextStepTaskId();
                Long nextPtId = checkOutManagementService.getNextStepPtId();
                
                System.out.println("下一步参数:");
                System.out.println("  工作流任务ID: " + nextTaskId);
                System.out.println("  待办任务ID: " + nextPtId);
                
                // 返回成功信息和下一步参数
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("message", "解除合同提交成功");
                responseData.put("nextTaskId", nextTaskId);
                responseData.put("nextPtId", nextPtId);
                
                return success(responseData);
            } else {
                return error("解除合同提交失败");
            }
            
        } catch (Exception e) {
            System.out.println("Controller：解除合同提交异常: " + e.getMessage());
            e.printStackTrace();
            return error("解除合同提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交账单调整（步骤4）
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:edit')")
    @Log(title = "账单调整提交", businessType = BusinessType.UPDATE)
    @PostMapping("/submitBillAdjustment")
    public AjaxResult submitBillAdjustment(@RequestBody java.util.Map<String, Object> params)
    {
        System.out.println("=== Controller：账单调整提交开始 ===");
        System.out.println("接收到的参数: " + params);
        
        try {
            // ✅ 权限控制：只有退住审批员a (tuizhushenpiyuana) 才能进行账单调整操作
            String currentUsername = getUsername();
            System.out.println("=== 账单调整权限检查 ===");
            System.out.println("当前用户: " + currentUsername);
            
            if (!"tuizhushenpiyuana".equals(currentUsername)) {
                System.out.println("❌ 非退住审批员a，禁止进行账单调整操作");
                return error("只有退住审批员a才能进行账单调整操作");
            }
            
            System.out.println("✅ 退住审批员a，允许进行账单调整操作");
            
            // 1. 提取参数
            Long businessId = Long.parseLong(params.get("businessId").toString());
            
            // 处理 taskId - 避免空字符串
            String taskId = "";
            if (params.get("taskId") != null && !params.get("taskId").toString().trim().isEmpty()) {
                taskId = params.get("taskId").toString();
            }
            
            // 处理 ptId - 避免空字符串转Long
            Long ptId = null;
            if (params.get("ptId") != null && !params.get("ptId").toString().trim().isEmpty()) {
                try {
                    ptId = Long.parseLong(params.get("ptId").toString());
                } catch (NumberFormatException e) {
                    System.out.println("ptId 格式错误: " + params.get("ptId"));
                }
            }
            
            // 处理审批意见和状态
            String opinion = params.get("opinion") != null ? params.get("opinion").toString() : "同意";
            Integer auditStatus = 1; // 默认通过
            if (params.get("auditStatus") != null) {
                try {
                    auditStatus = Integer.parseInt(params.get("auditStatus").toString());
                } catch (NumberFormatException e) {
                    System.out.println("auditStatus 格式错误: " + params.get("auditStatus"));
                }
            }
            
            System.out.println("业务ID: " + businessId);
            System.out.println("当前任务ID: " + taskId);
            System.out.println("当前待办任务ID: " + ptId);
            System.out.println("审批意见: " + opinion);
            System.out.println("审核状态: " + auditStatus);
            
            // 2. ✅ 调用 Service 层处理所有业务逻辑
            int result = checkOutManagementService.submitBillAdjustment(businessId, taskId, ptId, opinion, auditStatus);
            
            System.out.println("=== Controller：账单调整提交完成 ===");
            
            if (result > 0) {
                // ✅ 获取下一步的参数
                String nextTaskId = checkOutManagementService.getNextStepTaskId();
                Long nextPtId = checkOutManagementService.getNextStepPtId();
                
                System.out.println("下一步参数:");
                System.out.println("  工作流任务ID: " + nextTaskId);
                System.out.println("  待办任务ID: " + nextPtId);
                
                // 返回成功信息和下一步参数
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("message", "账单调整提交成功");
                responseData.put("nextTaskId", nextTaskId);
                responseData.put("nextPtId", nextPtId);
                
                return success(responseData);
            } else {
                return error("账单调整提交失败");
            }
            
        } catch (Exception e) {
            System.out.println("Controller：账单调整提交异常: " + e.getMessage());
            e.printStackTrace();
            return error("账单调整提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交账单审批（步骤5）
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:edit')")
    @Log(title = "账单审批提交", businessType = BusinessType.UPDATE)
    @PostMapping("/submitBillApproval")
    public AjaxResult submitBillApproval(@RequestBody java.util.Map<String, Object> params)
    {
        System.out.println("=== Controller：账单审批提交开始 ===");
        System.out.println("接收到的参数: " + params);
        
        try {
            // ✅ 权限控制：只有退住审批员a (tuizhushenpiyuana) 才能进行账单审批操作
            String currentUsername = getUsername();
            System.out.println("=== 账单审批权限检查 ===");
            System.out.println("当前用户: " + currentUsername);
            
            if (!"tuizhushenpiyuana".equals(currentUsername)) {
                System.out.println("❌ 非退住审批员a，禁止进行账单审批操作");
                return error("只有退住审批员a才能进行账单审批操作");
            }
            
            System.out.println("✅ 退住审批员a，允许进行账单审批操作");
            
            // 1. 提取参数
            Long businessId = Long.parseLong(params.get("businessId").toString());
            
            // 处理 taskId - 避免空字符串
            String taskId = "";
            if (params.get("taskId") != null && !params.get("taskId").toString().trim().isEmpty()) {
                taskId = params.get("taskId").toString();
            }
            
            // 处理 ptId - 避免空字符串转Long
            Long ptId = null;
            if (params.get("ptId") != null && !params.get("ptId").toString().trim().isEmpty()) {
                try {
                    ptId = Long.parseLong(params.get("ptId").toString());
                } catch (NumberFormatException e) {
                    System.out.println("ptId 格式错误: " + params.get("ptId"));
                }
            }
            
            // 审批意见和审核状态
            String opinion = params.get("opinion") != null ? params.get("opinion").toString() : "";
            Integer auditStatus = params.get("auditStatus") != null ? 
                Integer.parseInt(params.get("auditStatus").toString()) : 1;
            
            System.out.println("业务ID: " + businessId);
            System.out.println("当前任务ID: " + taskId);
            System.out.println("当前待办任务ID: " + ptId);
            System.out.println("审批意见: " + opinion);
            System.out.println("审核状态: " + auditStatus);
            
            // 2. ✅ 调用 Service 层处理所有业务逻辑
            Map<String, Object> result = checkOutManagementService.submitBillApproval(businessId, taskId, ptId, opinion, auditStatus);
            
            System.out.println("=== Controller：账单审批提交完成 ===");
            System.out.println("Service返回结果: " + result);
            
            if (result != null && (Boolean) result.get("success")) {
                // 返回成功，包含第六步参数
                return success("账单审批提交成功").put("data", result);
            } else {
                return error("账单审批提交失败");
            }
            
        } catch (Exception e) {
            System.out.println("Controller：账单审批提交异常: " + e.getMessage());
            e.printStackTrace();
            return error("账单审批提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交副院长审批（步骤6）
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:edit')")
    @Log(title = "副院长审批提交", businessType = BusinessType.UPDATE)
    @PostMapping("/submitVicePresidentApproval")
    public AjaxResult submitVicePresidentApproval(@RequestBody java.util.Map<String, Object> params)
    {
        System.out.println("=== Controller：副院长审批提交开始 ===");
        System.out.println("接收到的参数: " + params);
        
        try {
            // ✅ 权限控制：只有退住审批员a (tuizhushenpiyuana) 才能进行副院长审批操作
            String currentUsername = getUsername();
            System.out.println("=== 副院长审批权限检查 ===");
            System.out.println("当前用户: " + currentUsername);
            
            if (!"tuizhushenpiyuana".equals(currentUsername)) {
                System.out.println("❌ 非退住审批员a，禁止进行副院长审批操作");
                return error("只有退住审批员a才能进行副院长审批操作");
            }
            
            System.out.println("✅ 退住审批员a，允许进行副院长审批操作");
            
            // 1. 提取参数
            Long businessId = Long.parseLong(params.get("businessId").toString());
            
            // 处理 taskId - 避免空字符串
            String taskId = "";
            if (params.get("taskId") != null && !params.get("taskId").toString().trim().isEmpty()) {
                taskId = params.get("taskId").toString();
            }
            
            // 处理 ptId - 避免空字符串转Long
            Long ptId = null;
            if (params.get("ptId") != null && !params.get("ptId").toString().trim().isEmpty()) {
                try {
                    ptId = Long.parseLong(params.get("ptId").toString());
                } catch (NumberFormatException e) {
                    System.out.println("ptId 格式错误: " + params.get("ptId"));
                }
            }
            
            // 审批意见和审核状态
            String opinion = params.get("opinion") != null ? params.get("opinion").toString() : "";
            Integer auditStatus = params.get("auditStatus") != null ? 
                Integer.parseInt(params.get("auditStatus").toString()) : 1;
            
            // 杂费金额
            Double miscFees = params.get("miscFees") != null ? 
                Double.parseDouble(params.get("miscFees").toString()) : 0.0;
            
            System.out.println("业务ID: " + businessId);
            System.out.println("当前任务ID: " + taskId);
            System.out.println("当前待办任务ID: " + ptId);
            System.out.println("审批意见: " + opinion);
            System.out.println("审核状态: " + auditStatus);
            System.out.println("杂费金额: " + miscFees);
            
            // 2. ✅ 调用 Service 层处理所有业务逻辑
            int result = checkOutManagementService.submitVicePresidentApproval(businessId, taskId, ptId, opinion, auditStatus, miscFees);
            
            System.out.println("=== Controller：副院长审批提交完成 ===");
            
            if (result > 0) {
                // ✅ 获取下一步的参数
                String nextTaskId = checkOutManagementService.getNextStepTaskId();
                Long nextPtId = checkOutManagementService.getNextStepPtId();
                
                System.out.println("下一步参数:");
                System.out.println("  工作流任务ID: " + nextTaskId);
                System.out.println("  待办任务ID: " + nextPtId);
                
                // 返回成功信息和下一步参数
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("message", "副院长审批提交成功");
                responseData.put("nextTaskId", nextTaskId);
                responseData.put("nextPtId", nextPtId);
                
                return success(responseData);
            } else {
                return error("副院长审批提交失败");
            }
            
        } catch (Exception e) {
            System.out.println("Controller：副院长审批提交异常: " + e.getMessage());
            e.printStackTrace();
            return error("副院长审批提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交费用清算（步骤7 - 最后一步）
     */
    @PreAuthorize("@ss.hasPermi('system:out_management:edit')")
    @PostMapping("/submitBillSettlement")
    public AjaxResult submitBillSettlement(@RequestBody java.util.Map<String, Object> params)
    {
        System.out.println("=== Controller：费用清算提交开始（步骤7）===");
        System.out.println("接收到的参数: " + params);
        
        try {
            // ✅ 权限控制：只有退住审批员a (tuizhushenpiyuana) 才能进行费用清算操作
            String currentUsername = getUsername();
            System.out.println("=== 费用清算权限检查 ===");
            System.out.println("当前用户: " + currentUsername);
            
            if (!"tuizhushenpiyuana".equals(currentUsername)) {
                System.out.println("❌ 非退住审批员a，禁止进行费用清算操作");
                return error("只有退住审批员a才能进行费用清算操作");
            }
            
            System.out.println("✅ 退住审批员a，允许进行费用清算操作");
            
            // 1. 提取参数
            Long businessId = Long.parseLong(params.get("businessId").toString());
            
            // 处理 taskId - 避免空字符串
            String taskId = "";
            if (params.get("taskId") != null && !params.get("taskId").toString().trim().isEmpty()) {
                taskId = params.get("taskId").toString();
            }
            
            // 处理 ptId - 避免空字符串转Long
            Long ptId = null;
            if (params.get("ptId") != null && !params.get("ptId").toString().trim().isEmpty()) {
                try {
                    ptId = Long.parseLong(params.get("ptId").toString());
                } catch (NumberFormatException e) {
                    System.out.println("ptId 格式错误: " + params.get("ptId"));
                }
            }
            
            // 审批意见和审核状态
            String opinion = params.get("opinion") != null ? params.get("opinion").toString() : "";
            Integer auditStatus = params.get("auditStatus") != null ? 
                Integer.parseInt(params.get("auditStatus").toString()) : 1;
            
            // 老人ID和退款金额（用于退款逻辑）
            Long elderlyId = null;
            if (params.get("elderlyId") != null && !params.get("elderlyId").toString().trim().isEmpty()) {
                try {
                    elderlyId = Long.parseLong(params.get("elderlyId").toString());
                } catch (NumberFormatException e) {
                    System.out.println("elderlyId 格式错误: " + params.get("elderlyId"));
                }
            }
            
            Double refundAmount = null;
            if (params.get("refundAmount") != null && !params.get("refundAmount").toString().trim().isEmpty()) {
                try {
                    refundAmount = Double.parseDouble(params.get("refundAmount").toString());
                } catch (NumberFormatException e) {
                    System.out.println("refundAmount 格式错误: " + params.get("refundAmount"));
                }
            }
            
            System.out.println("业务ID: " + businessId);
            System.out.println("工作流任务ID: " + taskId);
            System.out.println("待办任务ID: " + ptId);
            System.out.println("审批意见: " + opinion);
            System.out.println("审核状态: " + auditStatus);
            System.out.println("老人ID: " + elderlyId);
            System.out.println("退款金额: " + refundAmount);
            
            // 2. 调用Service层提交
            int result = checkOutManagementService.submitBillSettlement(businessId, taskId, ptId, opinion, auditStatus, elderlyId, refundAmount);
            
            // 3. 如果提交成功且审批通过，执行退款逻辑
            if (result > 0 && auditStatus == 1 && elderlyId != null && refundAmount != null && refundAmount > 0) {
                System.out.println("=== 开始执行退款逻辑 ===");
                try {
                    // 调用退款API
                    java.util.Map<String, Object> refundData = new java.util.HashMap<>();
                    refundData.put("elderlyId", elderlyId);
                    refundData.put("refundAmount", refundAmount);
                    
                    System.out.println("退款数据: " + refundData);
                    
                    // 调用真正的退款服务
                    System.out.println("=== 开始调用updatePrepaymentBalance ===");
                    AjaxResult refundResult = balanceController.updatePrepaymentBalance(refundData);
                    System.out.println("退款结果: " + refundResult);
                    
                    if (refundResult.get("code").equals(200)) {
                        System.out.println("✅ 退款成功！");
                    } else {
                        System.out.println("❌ 退款失败: " + refundResult.get("msg"));
                    }
                    
                } catch (Exception e) {
                    System.err.println("❌ 退款处理异常: " + e.getMessage());
                    e.printStackTrace();
                    System.out.println("⚠️ 退款处理异常，但费用清算已成功");
                }
            }
            
            System.out.println("=== Controller：费用清算提交完成 ===");
            
            return result > 0 ? success("费用清算提交成功，退住流程已完成！") : error("费用清算提交失败");
            
        } catch (Exception e) {
            System.out.println("Controller：费用清算提交异常: " + e.getMessage());
            e.printStackTrace();
            return error("费用清算提交失败：" + e.getMessage());
        }
    }
}
